package cn.edu.swu.ws.controller;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class AuthFilter implements Filter {

    // 不需要登录就可以访问的路径
    private static final String[] ALLOWED_PATHS = {
            "/login.html",
            "/login",
            "/captcha",
            "/css/",
            "/home.html",
            "/"  // 根路径
    };

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession(false);

        String path = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());

        System.out.println("🔍 过滤器检查路径: " + path);

        // 检查是否在允许列表中
        if (isAllowedPath(path)) {
            System.out.println("✅ 允许访问（公开路径）: " + path);
            chain.doFilter(request, response);
            return;
        }

        // 检查是否已登录
        if (session != null && session.getAttribute("user") != null) {
            System.out.println("✅ 用户已登录，允许访问: " + path);
            chain.doFilter(request, response);
        } else {
            System.out.println("❌ 未登录，重定向到登录页面: " + path);
            // 保存原始请求路径，登录后可以跳转回来
            session = httpRequest.getSession(true);
            session.setAttribute("originalRequest", path);
            // 重定向到登录页面
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.html");
        }
    }

    private boolean isAllowedPath(String path) {
        if (path == null) return false;

        // 精确匹配或前缀匹配
        for (String allowedPath : ALLOWED_PATHS) {
            if (path.equals(allowedPath) ||
                    (allowedPath.endsWith("/") && path.startsWith(allowedPath)) ||
                    (allowedPath.endsWith(".html") && path.equals(allowedPath))) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("🛡️ AuthFilter 初始化完成 - 开始保护资源");
    }

    @Override
    public void destroy() {
        System.out.println("🛡️ AuthFilter 销毁");
    }
}